package com.example.contentprovider

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri

class MyContentProvider : ContentProvider() {

    private val bookDir = 0
    private val bookItem = 1
    private val categoryDir = 2
    private val categoryItem = 3
    private val authority = "com.example.contentprovider.provider"
    private var dbHelper:MyDB? = null


    private val uriMatcher by lazy {
        val matcher = UriMatcher(UriMatcher.NO_MATCH)
        matcher.addURI(authority,"book", bookDir)
        matcher.addURI(authority,"book/#", bookItem)
        matcher.addURI(authority,"category", categoryDir)
        matcher.addURI(authority,"category/#", categoryItem)
        matcher
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
        TODO("Implement this to handle requests to delete one or more rows")
    }

    override fun getType(uri: Uri): String? = when(uriMatcher.match(uri)){
        bookDir->"vnd.android.cursor.dir/vnd.$authority.book"
        bookItem->"vnd.android.cursor.item/vnd.$authority.book"
        categoryDir->"vnd.android.cursor.dir/vnd.$authority.category"
        categoryItem->"vnd.android.cursor.item/vnd.$authority.category"
        else->null
    }



    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        TODO("Implement this to handle requests to insert a new row.")
    }

    override fun onCreate() = context?.let {
        dbHelper = MyDB(it, "bookstore.db", 1)
        true
    }?:false

    override fun query(
        uri: Uri, projection: Array<String>?, selection: String?,
        selectionArgs: Array<String>?, sortOrder: String?
    ): Cursor? = dbHelper?.let{
        val db = it.readableDatabase
        val cursor = when(uriMatcher.match(uri)){
            bookDir->db.query("book", projection, selection, selectionArgs, null, null, sortOrder)
            bookItem->{
                val id = uri.pathSegments[1]
                db.query("book", projection, "id = ?" , arrayOf(id), null, null, sortOrder)
            }
            categoryDir->db.query("category", projection, selection, selectionArgs, null, null, sortOrder)
            categoryItem->{
                val id = uri.pathSegments[1]
                db.query("category", projection, "id = ?" , arrayOf(id), null, null, sortOrder)
            }
            else->null
        }
        cursor
    }

    override fun update(
        uri: Uri, values: ContentValues?, selection: String?,
        selectionArgs: Array<String>?
    ): Int {
        TODO("Implement this to handle requests to update one or more rows.")
    }
}